package com.fzkj.juc.readwritelock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @DESCRIPTION 缓存小工具
 */
public class SimpleCache {

    private volatile Map<String, Object> map = new HashMap<>();
    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String key, Object value){
        lock.writeLock().lock();
        try{
            System.out.println(key + "\t 正在写入 \t" + key);
            map.put(key, value);
            System.out.println(key + "\t 写入完成");
        }finally {
            lock.writeLock().unlock();
        }

    }

    public Object get(String key){
        lock.readLock().lock();
        try{
            System.out.println(key + "\t 正在读取");
            Object o = map.get(key);
            System.out.println(key + "\t 读取完成 \t" + o);
            return o;
        }finally {
            lock.readLock().unlock();
        }

    }

    public void clear(){
        map.clear();
    }
}
